package com.yunshang.ysmall.controller;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.yunshang.ysmall.model.OrderInfo;
import com.yunshang.ysmall.model.OrderItemInfo;
import com.yunshang.ysmall.model.ReturnFanchang;
import com.yunshang.ysmall.service.SalesReturnService;
import com.yunshang.ysmall.util.Constants;
import com.yunshang.ysmall.util.DateUtils;
import com.yunshang.ysmall.util.HttpClientUtils;
import com.yunshang.ysmall.util.MD5Utils;


@Controller
@RequestMapping("/sales")
public class SalesReturnController {
	private static Logger logger = LoggerFactory.getLogger(OrderController.class);
	@Resource
	SalesReturnService salesReturnService;
	
	 //前台页面：查询所有的正在退货的订单.也就是状态为1的订单
	@RequestMapping("showSalesReturnManager")
	public String findSalesReturnInfoList(HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}		
		//根据会员编号查询正在退款的信息
		List<ReturnFanchang> returnFanchangs=salesReturnService.findSalesReturnAll((String)request.getSession().getAttribute(Constants.MEMBER_ID));
		//根据订单号去查询购买的产品
		List<OrderInfo> orders= new ArrayList<OrderInfo>();
		for (ReturnFanchang returnFanchang : returnFanchangs) {
			//根据订单编号查询所有的订单详细信息
			OrderInfo orderInfo=salesReturnService.findOrderItemInfo(returnFanchang.getOrderId());
			orders.add(orderInfo);
		}
		model.addAttribute("orders",orders);
		model.addAttribute("salesReturnLength", orders.size());
		return "/mall/salesreturnmanager";
	}
	

	
	//后台用户管理
	@RequestMapping("/returnOrder")
	public String greenroomSalesReturnManager(ReturnFanchang returnFanchang,Model model){
		Map<String,Object> parameter=new  HashMap<String, Object>();
		if(returnFanchang!=null&&returnFanchang.getMemberId()!=null){
			parameter.put("memberId",returnFanchang.getMemberId());
		}
		if(returnFanchang!=null&&returnFanchang.getOrderId()!=null){
			parameter.put("orderId",returnFanchang.getOrderId());
		}
		parameter.put("startSubscript",0);
		parameter.put("findCount",10000);
		List<ReturnFanchang> returnFanchangs=salesReturnService.getSalesReturnList(parameter);
		model.addAttribute("returnFanchangs", returnFanchangs);
		return "/mng/main/salesreturnmanager/salesreturnlist";
	}
	
	//后台显示所有的待处理订单
	@RequestMapping("/pedingSalesReturn")
	public String pendingSalesReturnOrder( ReturnFanchang returnFanchang,Model model){
		Map<String,Object> parameter=new  HashMap<String, Object>();
		if(returnFanchang!=null&&returnFanchang.getMemberId()!=null){
			parameter.put("memberId",returnFanchang.getMemberId());
		}
		if(returnFanchang!=null&&returnFanchang.getOrderId()!=null){
			parameter.put("orderId",returnFanchang.getOrderId());
		}
		List<ReturnFanchang> returnFanchangs=salesReturnService.pedingSalesReturnList(parameter);
		model.addAttribute("listSize",returnFanchangs.size());
		model.addAttribute("pendingreturnFanchangs", returnFanchangs);
		return "/mng/main/salesreturnmanager/pendingsalesreturnlist";
	}
	
	//后台商品详情页面显示
	@RequestMapping("/itemDecription")
	public String itemDecription(String orderId,Model model){
		//根据订单的编号查询订单信息
		OrderInfo orderInfo=salesReturnService.selectOrderId(orderId);
		//根据订单编号查询购买的商品
		List<OrderItemInfo> orderItemInfos=salesReturnService.findProductAll(orderId);
		//通过订单编号查询退货信息
		ReturnFanchang returnFanchang=salesReturnService.findSalesReturnOrderId(orderId);
		model.addAttribute("orderItemInfos",orderItemInfos );
		model.addAttribute("returnFanchang", returnFanchang);
		model.addAttribute("orderInfo", orderInfo);
		return "/mng/main/salesreturnmanager/itemdescription";
	} 
	
	
	//修改待处理的订单
	@ResponseBody
	@RequestMapping("/updatePendingOrder")
	public String updatePending(HttpServletRequest request,@RequestParam String orderId){
		//返还积分的调用
		OrderInfo orderInfo=salesReturnService.findOrderInfo(orderId);
		if(returnBonus(orderInfo)){
			//修改退货表中的退货状态
			salesReturnService.updateSalesReturn(orderId);
			//修改订单表中的订单状态和物流状态
			salesReturnService.updateOrderInfoStatus(orderId);
			System.out.println("返回积分成功");
			
			return "{\"result\":\"success\"}";
		}else{
			System.out.println("返回积分不成功");
			return "{\"result\":\"comeToNothing\"}";
		}
	}
	
	//显示所有已处理的退货订单
	@RequestMapping("/endSalesReturn")
	public String endSalesReturn(ReturnFanchang returnFanchang,Model model){
		Map<String,Object> parameter=new HashMap<>();
		if(returnFanchang!=null&&returnFanchang.getOrderId()!=null){
			parameter.put("memberId", returnFanchang.getMemberId());
		}
		if(returnFanchang!=null&&returnFanchang.getOrderId()!=null){
			parameter.put("orderId", returnFanchang.getOrderId());
		}
      	List<ReturnFanchang> returnFanchangs=salesReturnService.findendSalesReturnAll(parameter);
      	model.addAttribute("processedSalesReturnOrders",returnFanchangs);
		return "/mng/main/salesreturnmanager/processedsalesreturnlist";
	}
	
	//填写退货的物流单号
	@RequestMapping("/updateSalesReturn")
	public String  updateSalesReturn(ReturnFanchang returnFanchang ){
		salesReturnService.updateSalesReturnTrackingNumber(returnFanchang);
		return "redirect:/sales/pedingSalesReturn";
	}
	
	//返还积分
	private static boolean returnBonus(OrderInfo orderInfo){
		try{
			String url ="http://www.yssy7.com/scapi.aspx?client_id=YUNSHANG08";
			String key ="ys123456";
			//转换的为："{"USER_ALIAS":""orderInfo"","PAY_TYPE":"3","MONEY":""orderInfo.getTransBonus()"","ORDER_NO":"""","PAY_IP":"127.0.0.1"}"
			String param = URLEncoder.encode("{\"USER_ALIAS\":\""+orderInfo.getMemberId()+"\",\"PAY_TYPE\":\"3\",\"MONEY\":\""+orderInfo.getTransBonus()+"\",\"ORDER_NO\":\""+orderInfo.getOrderId()+"\",\"DEAL_NUMBER\":\""+orderInfo.getBebitCode()+"\",\"PAY_IP\":\"127.0.0.1\"}","utf-8");
			//获取当前时间，转换为指定的格式
			String ndate = DateUtils.currentDate("HHmmss");
			//对传入的参数进行加密并且全部转换为小写
			String md5 = MD5Utils.MD5("YUNSHANG08"+key+ndate).toLowerCase();
			String requestUrl = url+"&schema_name=GET_USER_ACCOUNT_RETURN&parameter="+param+"&ndate="+ndate+"&md5="+md5;
			logger.info("requestUrl:"+requestUrl);
			String result = HttpClientUtils.httpGet(requestUrl);
			//讲结果输入到日志中
			logger.info("result:"+result);
		// {"result":"success","total":1,"data":[{"NAME":"乔江2","DWALLET":"0.74","USER_ALIAS":"AN809702","PASSWORD":"96e79218965eb72c92a549dd5a330112","ISLOGIN":1.0}]};
			//将获取的字符串转换为json对象
			JSONObject jsonObject = JSONObject.parseObject(result);
			//判断这个json对象中是否含有sucess值
			if("success".equals(jsonObject.getString("result"))){
				JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
				if ("1".equals(data.getString("ISREFUND").split("\\|")[0])) {
					return true;
				}
			}
			return false;
		}catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		
		
	}
}
